package api

import (
	"blogdemo/gin/errmsg"
	"blogdemo/gin/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Register 用户注册
func Register(c *gin.Context) {
	var user model.User
	// 绑定数据模型
	_ = c.ShouldBind(&user)

	if !model.CheckUserName(user.Username) {
		c.JSON(400, gin.H{
			"status": errmsg.USERNAME_INVALID,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.USERNAME_INVALID),
		})
		fmt.Println("username is invalid")
		c.Abort()
		return
	}

	if !model.CheckPhoneNumber(user.PhoneNumber) {
		c.JSON(400, gin.H{
			"status": errmsg.PNUMBER_INVALID,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.PNUMBER_INVALID),
		})
		fmt.Println("pNumber is invalid")
		c.Abort()
		return
	}

	if !model.CheckPassword(user.Password) {
		c.JSON(400, gin.H{
			"status": errmsg.PASSWORD_INVALID,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.PASSWORD_INVALID),
		})
		fmt.Println("password is invalid")
		c.Abort()
		return
	}

	findUser := model.FindUser(user.Username)
	if findUser {
		c.JSON(400, gin.H{
			"status": errmsg.USERNAME_EXIST,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.USERNAME_EXIST),
		})
		fmt.Println("username is exist")
		c.Abort()
		return
	}

	findPNumber := model.FindPhoneNumber(user.PhoneNumber)
	if findPNumber {
		c.JSON(400, gin.H{
			"status": errmsg.PNUMBER_EXIST,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.PNUMBER_EXIST),
		})
		fmt.Println("pNumber is exist")
		c.Abort()
		return
	}

	var msgCode int
	if !(findUser || findPNumber) {
		msgCode = model.AddUser(&user)
	}
	if msgCode == errmsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H{
			"status": errmsg.SUCCESS,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.SUCCESS),
		})
		// 初始化个人资料
		profile := model.Profile{Username: user.Username, Nickname: user.Username}
		model.InitProfile(&profile)
		fmt.Println("用户注册成功")
	} else {
		c.JSON(400, gin.H{
			"status": errmsg.FAIL,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.FAIL),
		})
		fmt.Println("用户注册失败")
	}
}
